'''
Created on 28/01/2013

@author: Milo
'''
from MaltegoTransform import MaltegoTransform
from ToMaltego import add_author
from BibTeXParser import  BibTeXParser
import sys, os

'''Variables'''
transform = MaltegoTransform()
parser = BibTeXParser()

#Last argument is entity property values, '#' is added at end to ensure correct formatting
values = sys.argv[-1]+"#"
bibtexfile = values[values.find("=")+1:values.find("#")]

'''Helper Functions'''

def find(occurrence_of, in_sequence):
    k = -1
    for item in in_sequence:
        k = k+1
        if occurrence_of == item: 
            return k
    return 0

def dictionary_to_string(dictionary):
    string = ""
    for item in dictionary:
        string = string + item
    return string

#Simple extension check
def is_bibtexfile(file_name):
    return file_name.endswith(".bib")
    
    

#'''Debug code'''
#transform.addUIMessage("VALUES are: "+values)
#transform.addUIMessage("BIBTEX is: "+bibtexfile)

'''Progam Functions'''
'''Document to author'''
def do_transformation():
    transform.addUIMessage("Author transformation from Bibtex file beginning.")
    
    count = 0
    while count < len(results):
        biblography = results[count]
        authors = biblography['author'].split()
    
        #Author format specific hack
        i = 0
        done = False
        while i != -1:
            i = 0
            j = find('and', authors)
            if j == 0:
                j = len(authors)
                done = True
            #Special case of organisation not person
            if find(",", authors[i:j]) == 0:
                name = ""
                for part in authors[i:j]:
                    name = name + part + " "
                #Remove last space
                name = name[:len(name)-1]
                add_author(transform, name, "")
            else:
                lastname = authors[i]
                firsnameslist = authors[i+1:j]
                firstnames = ""
                for name in firsnameslist:
                    firstnames = firstnames + name + " "
                #Remove last space
                firstnames = firstnames[:len(firstnames)-1]
                lastname = lastname.replace(",", "")
                add_author(transform, firstnames, lastname) 
            authors = authors[j+1:]
            #Case of last part
            if done:
                i = -1
        count = count + 1
    
    transform.addUIMessage("Author transformation from Bibtex completed!")

'''Transformation code'''
#Attempt to use the file path given
if os.path.isfile(bibtexfile) and is_bibtexfile(bibtexfile):
    try:
        results = parser.parse(bibtexfile)
        do_transformation()
    except IOError as e:
        transform.addUIMessage("File not available: "+ e)
else:
    transform.addUIMessage("File not available")

transform.returnOutput()
